<?php

namespace app\common\model;

use think\facade\Db;


class GoodsSpecModel extends CommonModel{

    protected  $name = 'beautiful_goods_spec';

    protected  $pk   = 'id';


    public static function info($where){
        $info = Db::name('beautiful_goods_spec')->alias('a')
            ->where(['a.is_delete'=>0])
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(!empty($where['id']),function ($query) use ($where){
                $query->where(['a.id'=>$where['id']]);
            })
            ->when(!empty($where['name']),function ($query) use ($where){
                $query->where('a.name','like','%'.$where['name'].'%');
            })
            ->field("a.*")
            ->find();
        if(!empty($info)){
            $spec_text=json_decode($info['spec_text'],true);
//            usort($spec_text,function ($a,$b){
//                if($a['sort']==$b['sort']){
//                    return 0;
//                }
//                return ($a['sort'] < $b['sort']) ? -1 : 1;
//            });
            $info['spec_text']=$spec_text;
        }
        return $info;
    }
    public static function list($where,$order=['a.id'=>'desc'],$page=1,$limit=10){
        $query = Db::name('beautiful_goods_spec')->alias('a')
            ->where(['a.is_delete'=>0])
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(!empty($where['name']),function ($query) use ($where){
                $query->where('a.name','like','%'.$where['name'].'%');
            })
            ->field("a.*");
        $count=$query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$v){
                $spec_text=json_decode($v['spec_text'],true);
//                usort($spec_text,function ($a,$b){
//                    if($a['sort']==$b['sort']){
//                        return 0;
//                    }
//                    return ($a['sort'] < $b['sort']) ? -1 : 1;
//                });
                $v['spec_text']=$spec_text;
            }
        }
        return compact('count','list');
    }
    public static function up($data,$where){
        $data['edit_time']=date('Y-m-d H:i:s');
        $res=self::update($data,$where);
        return $res;
    }
    public static function getById($where,$field='*')
    {
        $list = Db::name('beautiful_goods_spec')->where($where)->field($field)->find();

        return $list;
    }
}

